import base64
from django.http import JsonResponse
from rest_framework.views import APIView
from app01 import models
from app01.woutils import user_jwt
# Create your views here.
from app01.woutils.encryption import aes_encrypt


class User_Login(APIView):
    '''登录'''
    def post(self,request):
        #获取提交的内容
        username = request.data.get('username', "未填写账号")
        password = request.data.get('password', "未填写密码")
        #查询账号是否存在
        user_info = models.UserInfo.objects.filter(username=username).first()
        if not user_info:
            data = {'code': 503, "msg": "账号或密码错误", 'data': ''}
            return JsonResponse(data)

        #将密码进行加密
        password = base64.b64encode(aes_encrypt(password.encode('utf-8'))).decode('utf-8')

        #将加密后的密码 与数据库中的密码进行对比
        if not password == user_info.password:
            data = {'code': 503, "msg": "账号或密码错误", 'data': ''}
            return JsonResponse(data)

        #将用户信息加密为token 作为用户凭证
        token = user_jwt.GenToken(user_info.username, user_info.level)  # 将用户名和用户等级 进行jwt数据加密 生成token

        #设置返回的json
        datas = {
            "code": 200,
            "msg": "登陆成功",
            "data": {
                "token": token,
                "name": user_info.name,
                "username": user_info.username,
                "level": user_info.level
            }
        }
        return JsonResponse(datas)
